#!/user/bin/env python3
# -*- coding: utf-8 -*-


# import os
# import logging.handlers
# import logging
# import time
# from Common.get_path import *
#
# log_path = os.path.join(get_path(), 'Logs')
# a = os.path.exists(log_path)
# if not a:  # 判断a路径是否存在，不存在则创建一个路径文件夹
#     os.mkdir(log_path)
#
#
# class Loggers:
#     """
#     日志处理类
#     """
#
#     def __init__(self):
#         # 初始化创建一个带时间戳的log文件
#         self.logname = os.path.join(log_path, '{0}.log'.format(time.strftime('%Y-%m-%d')))
#
#     def __printconsole(self, level, message):
#         # 创建一个logger
#         logger = logging.getLogger()
#         logger.setLevel(logging.DEBUG)
#         # 创建一个handler,用于写入日志文件
#         fh = logging.FileHandler(self.logname, 'a', encoding='utf-8')
#         fh.setLevel(logging.DEBUG)
#         # 再创建一个handler,用于输出到控制台
#         ch = logging.StreamHandler()
#         ch.setLevel(logging.DEBUG)
#         # 定义handler的输出格式
#         formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#         fh.setFormatter(formatter)
#         ch.setFormatter(formatter)
#         # 给logger添加handler
#         logger.addHandler(fh)
#         logger.addHandler(ch)
#         # 记录一条日志
#         if level == 'info':
#             logger.info(message)
#         elif level == 'debug':
#             logger.debug(message)
#         elif level == 'warning':
#             logger.warning(message)
#         elif level == 'error':
#             logger.error(message)
#         logger.removeHandler(ch)
#         logger.removeHandler(fh)
#         # 关闭打开的文件
#         fh.close()
#
#     def debug(self, message):
#         """
#         :param message: debug信息
#         :return:
#         """
#         self.__printconsole('debug', message)
#
#     def info(self, message):
#         """
#         :param message: info信息
#         :return:
#         """
#         self.__printconsole('info', message)
#
#     def warning(self, message):
#         """
#         :param message:warn信息
#         :return:
#         """
#         self.__printconsole('warning', message)
#
#     def error(self, message):
#         """
#         :param message:error信息
#         :return:
#         """
#         self.__printconsole('error', message)


# if __name__ == "__main__":
#     mylogger = Loggers()
#     mylogger.info("info......")
#     mylogger.warning('warn……')
#     mylogger.error('error……')
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from Common.getpath import *


class Logger:
    def __init__(self, logger_name='logs…'):
        global log_path
        path = get_root_path()
        log_path = os.path.join(path, 'Logs')  # 存放log文件的路径
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        self.log_file_name = 'logs'  # 日志文件的名称
        self.backup_count = 5  # 最多存放日志的数量
        # 日志输出级别
        self.console_output_level = 'WARNING'
        self.file_output_level = 'DEBUG'
        # 日志输出格式
        self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    def get_logger(self):
        """在logger中添加日志句柄并返回，如果logger已有句柄，则直接返回"""
        if not self.logger.handlers:  # 避免重复日志
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(self.formatter)
            console_handler.setLevel(self.console_output_level)
            self.logger.addHandler(console_handler)

            # 每天重新创建一个日志文件，最多保留backup_count份
            file_handler = TimedRotatingFileHandler(filename=os.path.join(log_path, self.log_file_name), when='D',
                                                    interval=1, backupCount=self.backup_count, delay=True,
                                                    encoding='utf-8')
            file_handler.setFormatter(self.formatter)
            file_handler.setLevel(self.file_output_level)
            self.logger.addHandler(file_handler)
        return self.logger


# Logger().get_logger().info("111111111111111")
#
# if __name__ == "__main__":
#     pass